package com.koron.order.defect.plugin;

import com.alibaba.fastjson.JSON;
import com.koron.bean.base.Response;
import com.koron.bean.system.post.query.PostUserQuery;
import com.koron.bean.system.post.vo.PostUserVo;
import com.koron.bean.workflow.SubmitterParam;
import com.koron.bean.workflow.WorkflowUser;
import com.koron.common.core.business.datadict.service.SysDataDictService;
import com.koron.common.core.business.datadict.utils.DataDictTool;
import com.koron.common.core.business.system.feign.SystemFeignService;
import com.koron.common.core.business.workflow.templates.WorkFlowHandler;
import com.koron.order.defect.bean.po.DefectBean;
import com.koron.order.defect.controller.DefectController;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName DefectWaitReviewPlugin
 * @description 测试水司缺陷待审核选人规则
 * @Author zhouj
 * @Date 2022/1/12 18:52
 */
@Slf4j
@RequestMapping("/defect/plugin/waitReview/")
@RestController
@Api(tags = "缺陷工单-待审核插件")
public class DefectWaitReviewPlugin {

    @Autowired
    private WorkFlowHandler workFlowHandler;

    @Autowired
    private DefectController defectController;

    @Autowired
    private SysDataDictService sysDataDictService;

    @Autowired
    private SystemFeignService systemFeignService;

    //设备管理单位领导审核 节点配置出口规则
    @PostMapping("/task1/submitter")
    public Response<List<WorkflowUser>> submitter1(@RequestBody SubmitterParam submitterParam) {

        String formVariables = submitterParam.getFormVariables();
        List<WorkflowUser> workflowUsers = submitterParam.getUsers();

        //返回对象
        List<WorkflowUser> result = new ArrayList<>();

        DefectBean defectBean = getBussinessBean(submitterParam);
        /*
                节点1的过滤处理  设备管理单位领导审核
                1、处理人	站长（岗位）、副站长（岗位）、安全主任（岗位）
                2、必须变更审核人的节点	无
                3、选人组件过滤规则	只能选择缺陷工单的设备管理单位下的人
                4、操作类型	沟通、转办、驳回
                5、通知方式	待办
                */
        //先根据业务id查询出缺陷工单的设备管理单位信息(且需要拿到组织该节点的子级节点(暂不考虑))，同节点的处理人所属单位进行比较，相同或包含则返回

        //设备管理单位
        String deptManage = defectBean.getDeptManage();
        String deptManageName = defectBean.getDeptManageName();

        List<String> orgIdList = new ArrayList<>();
        orgIdList.add(deptManage);

        /*name code type*/
        //先分类
        List<WorkflowUser> gwList = workflowUsers.stream().filter(p -> 2 == p.getType()).collect(Collectors.toList());

        Assert.notEmpty(gwList, "配置的岗位不能为空");

        //分别通过各自id/code进行查询，或者过滤，最终转化为人员
        List<String> gwIdList = gwList.stream().map(WorkflowUser::getCode).collect(Collectors.toList());

        //先将岗位转化为对应的人员列表，利用人员的单位==缺陷工单的设备管理单位
        PostUserQuery postUserQuery = new PostUserQuery();
        postUserQuery.setPostIdList(gwIdList);
        postUserQuery.setOrgIdList(orgIdList);
        //拿到岗位下的人
        List<PostUserVo> postUserVos = getPostList(postUserQuery);

        //转换为返回对象
        convertUser(postUserVos, result);

        return Response.ok(result);
    }

    @PostMapping("/task2/submitter")
    public Response<List<WorkflowUser>> submitter2(@RequestBody SubmitterParam submitterParam) {
        /*
        1、节点2的过滤处理
        2、处理人	XX部/XX室/ 主任（岗位）、XX部/XX室/ 副主任（岗位）、XX部副总经理 部门副总经理（岗位）
        3、选人组件过滤规则	自动发给当前缺陷工单的专业对应的人。
        4、操作类型	沟通、转办、驳回
        5、通知方式	待办
        */
        List<WorkflowUser> workflowUsers = submitterParam.getUsers();
        //主要根据专业来筛选
        DefectBean defectBean = getBussinessBean(submitterParam);

        List<WorkflowUser> result = new ArrayList<>();

        //根据缺陷工单的专业--通过字典转化为中文
        String major = defectBean.getMajor();
        String major_dict = major;

        //下面为获取可用列表
        Map<String, String> dataDictByCode = DataDictTool.getDataDictByCode("publicDictionary", "common_major");
        major_dict = dataDictByCode.get(major);

        String major_dict_A = major_dict + "室";

        /*name code type*/
        //先分类
        List<WorkflowUser> gwList = workflowUsers.stream().filter(p -> 2 == p.getType()).collect(Collectors.toList());

        Assert.notEmpty(gwList, "配置的岗位不能为空");

        //分别通过各自id/code进行查询，或者过滤，最终转化为人员
        List<String> gwIdList = gwList.stream().map(WorkflowUser::getCode).collect(Collectors.toList());

        PostUserQuery postUserQuery = new PostUserQuery();
        postUserQuery.setPostIdList(gwIdList);

        if ("综合".equals(major_dict)) {
            postUserQuery.setPostNameList(Arrays.asList(new String[]{"部门副总经理"}));
            postUserQuery.setParentOrgNameList(Arrays.asList(new String[]{"维修部"}));
        } else {
            postUserQuery.setParentOrgNameList(Arrays.asList(new String[]{major_dict_A}));
        }

        //拿到岗位下的人
        List<PostUserVo> postUserVos = getPostList(postUserQuery);

        convertUser(postUserVos, result);

        return Response.ok(result);
    }

    //技术部审核 节点配置入口规则
    @PostMapping("/task3/submitter")
    public Response<List<WorkflowUser>> submit3(@RequestBody SubmitterParam submitterParam) {
        //节点3的过滤处理

        /*
        1、处理人	生产技术部自动化管理（岗位）、生产技术部电气管理（岗位）、生产技术部机械管理（岗位）、生产技术部通讯管理（岗位）、生产技术部负责人（岗位）
        2、选人组件过滤规则	自动发送给当前缺陷工单的专业对应的人员。补充说明：各专业发给技术部各专业管理人员，综合专业发给生产技术部负责人
        3、操作类型	沟通、转办、驳回
        4、通知方式	待办
        */

        List<WorkflowUser> workflowUsers = submitterParam.getUsers();
        //主要根据专业来筛选
        DefectBean defectBean = getBussinessBean(submitterParam);

        List<WorkflowUser> result = new ArrayList<>();

        //根据缺陷工单的专业--通过字典转化为中文
        String major = defectBean.getMajor();
        String major_dict = major;

        //下面为获取可用列表
        Map<String, String> dataDictByCode = DataDictTool.getDataDictByCode("publicDictionary", "common_major");
        major_dict = dataDictByCode.get(major);

        /*name code type*/
        //先分类
        List<WorkflowUser> gwList = workflowUsers.stream().filter(p -> 2 == p.getType()).collect(Collectors.toList());

        Assert.notEmpty(gwList, "配置的岗位不能为空");

        //分别通过各自id/code进行查询，或者过滤，最终转化为人员
        List<String> gwIdList = gwList.stream().map(WorkflowUser::getCode).collect(Collectors.toList());

        PostUserQuery postUserQuery = new PostUserQuery();

        postUserQuery.setPostIdList(gwIdList);

        if ("综合".equals(major_dict)) {
            //只拿 生产技术部负责人(岗位的人)
            postUserQuery.setPostName("生产技术部负责人");
        } else {
            postUserQuery.setPostName(major_dict);
        }

        //拿到岗位下的人
        List<PostUserVo> postUserVos = getPostList(postUserQuery);

        convertUser(postUserVos, result);

        return Response.ok(result);

    }


    private DefectBean getBussinessBean(SubmitterParam submitterParam) {
        return JSON.parseObject(submitterParam.getFormVariables(), DefectBean.class);
    }

    private List<PostUserVo> getPostList(PostUserQuery postUserQuery) {
        Response<List<PostUserVo>> listResponse = systemFeignService.queryPostList(postUserQuery);
        List<PostUserVo> postUserVos = listResponse.getData();
        return postUserVos;
    }

    private void convertUser(List<PostUserVo> postUserVos, List<WorkflowUser> result) {
        //转换为返回对象
        if (CollectionUtils.isEmpty(postUserVos)) {
            return;
        }
        for (PostUserVo postUserVo : postUserVos) {
            WorkflowUser workflowUser = new WorkflowUser();
            workflowUser.setCode(postUserVo.getUserAccount());
            workflowUser.setName(postUserVo.getUserName());
            result.add(workflowUser);
        }
    }

}
